#!/bin/bash -e

# DDR Test Script
# 支持参数：
#   -l    循环模式
#   -t N  启动 N 个线程（默认1）
#   -s    指定测试内存大小（默认1G）
#   -i N  指定迭代次数（默认1000）
#   -d N  每次循环间隔时间（默认60秒）

LOOP=false
THREADS=1
SIZE=1G
ITERATIONS=1000
DURATION=60
LOG_DIR="$HOME/stability-test-log"
mkdir -p "$LOG_DIR"

while getopts "lt:s:i:d:h" opt; do
    case $opt in
        l)
            LOOP=true
            ;;
        t)
            THREADS=$OPTARG
            ;;
        s)
            SIZE=$OPTARG
            ;;
        i)
            ITERATIONS=$OPTARG
            ;;
        d)
            DURATION=$OPTARG
            ;;
        h)
            echo "Usage: $0 [-l] [-t THREADS] [-s SIZE] [-i ITERATIONS] [-d DURATION]"
            echo "Options:"
            echo "  -l          Loop mode"
            echo "  -t N        Number of threads (default: 1)"
            echo "  -s SIZE     Memory size per test (default: 1G)"
            echo "  -i N        Iterations (default: 1000)"
            echo "  -d N        Duration between loops (default: 60s)"
            exit 0
            ;;
        \?)
            exit 1
            ;;
    esac
done

command -v memtester > /dev/null || (sudo apt update && sudo apt install -y memtester)

run_memtester() {
    local idx=$1
    local logfile="$LOG_DIR/memtester.log.$idx"
    echo "Starting memtester thread $idx logging to $logfile"

    if $LOOP; then
        while true; do
            echo "[`date`] memtester $SIZE 1" >> "$logfile"
            memtester "$SIZE" 1 >> "$logfile" 2>&1
            echo "Sleeping for $DURATION seconds..." >> "$logfile"
            sleep "$DURATION"
        done &
    else
        echo "[`date`] memtester $SIZE $ITERATIONS" > "$logfile"
        memtester "$SIZE" "$ITERATIONS" >> "$logfile" 2>&1 &
    fi
}

for ((i=0; i<THREADS; i++)); do
    run_memtester $i
done

echo "DDR test started, logs are saved to $LOG_DIR/memtester.log.*"

